<script setup lang="ts">
defineOptions({
  name: "Survey"
});

import { ref, reactive, onMounted, watch } from "vue";
import {
  ElButton,
  ElInput,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElMessage,
  ElMessageBox,
  ElDialog,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElInput as ElTextarea
} from "element-plus";
import { Search, Plus } from "@element-plus/icons-vue";
import {
  getQuestionnaireList,
  deleteQuestionnaire,
  addQuestionnaire,
  getQuestionnaireDetail,
  updateQuestionnaire,
  type QuestionnaireQueryParams,
  type QuestionnaireSurveyListVo,
  type QuestionnaireSurveyAddDto,
  type QuestionnaireSurveyUpdateDto,
  type QuestionAddDto,
  type QuestionDetailVo,
  type QuestionDto,
  type QuestionOption,
  addQuestion,
  getQuestionDetail,
  getQuestionsByQuestionnaireId,
  updateQuestion,
  deleteQuestion,
  getAllQuestionOptions,
  addQuestionOption,
  deleteQuestionOption,
  updateQuestionOption,
  deleteAllQuestionOptions,
  updateQuestionOptionsSort,
  updateQuestionSort,
  searchQuestionnaireByKeyword
} from "@/api/questionnaire";
import { findAllCells } from "@/api/cell";

// 响应式数据
const loading = ref(false);
const surveyList = ref<QuestionnaireSurveyListVo[]>([]);
const searchKeyword = ref("");
const communities = ref<any[]>([]);
const communityLoading = ref(false);

// 分页数据
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0
});

// 新增问卷对话框
const addDialogVisible = ref(false);
const addForm = reactive<QuestionnaireSurveyAddDto>({
  cellId: undefined,
  questionnaireName: "",
  questionnaireDescription: "",
  participationScope: "全体业主",
  publishTime: "",
  endTime: ""
});
const addFormLoading = ref(false);
const addFormRef = ref<InstanceType<typeof ElForm>>();

// 编辑问卷对话框
const editDialogVisible = ref(false);
const editForm = reactive<QuestionnaireSurveyUpdateDto>({
  id: 0,
  cellId: 0,
  questionnaireName: "",
  questionnaireDescription: "",
  participationScope: "全体业主",
  publishTime: "",
  endTime: ""
});
const editFormLoading = ref(false);
const editFormRef = ref<InstanceType<typeof ElForm>>();
const activeEditTab = ref("info"); // 'info' 编辑问卷信息, 'questions' 编辑问题信息

const handleQuestionsConfirm = () => {
  ElMessage.success('操作完成')
  editDialogVisible.value = false
  // 刷新问卷列表
  fetchSurveyList()
}

// 问题相关数据
const questions = ref<QuestionDetailVo[]>([]);
const addQuestionDialogVisible = ref(false);
const addQuestionForm = reactive<QuestionAddDto>({
  questionnaireId: 0,
  type: 1,
  question: "",
  isRequired: 1,
  sort: 1
});
const addQuestionLoading = ref(false);
const addQuestionFormRef = ref<InstanceType<typeof ElForm>>();

// 问题选项数据
const questionOptions = reactive<Map<number, QuestionOption[]>>(new Map());
const optionLoading = reactive<Map<number, boolean>>(new Map());

// 新增选项表单
const addOptionDialogVisible = ref(false);
const addOptionForm = reactive<Partial<QuestionOption>>({
  questionId: 0,
  content: ""
});
const addOptionLoading = ref(false);
const currentQuestionForOption = ref<QuestionDetailVo | null>(null);

// 编辑选项表单
const editOptionDialogVisible = ref(false);
const editOptionForm = reactive<QuestionOption>({
  id: 0,
  questionId: 0,
  content: "",
  sort: 1
});
const editOptionLoading = ref(false);
const currentOptionId = ref(0);

// 获取小区列表
const fetchCellList = async () => {
  try {
    communityLoading.value = true;
    const response = await findAllCells();
    if (response.code === 0 || response.code === 200) {
      communities.value = response.data || [];
    } else {
      ElMessage.error(response.message || "获取小区列表失败");
    }
  } catch (error) {
    console.error("获取小区列表失败:", error);
    ElMessage.error("获取小区列表失败");
  } finally {
    communityLoading.value = false;
  }
};

// 重置新增表单
const resetAddForm = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  Object.assign(addForm, {
    cellId: undefined,
    questionnaireName: "",
    questionnaireDescription: "",
    participationScope: "全体业主",
    publishTime: "",
    endTime: "",
    tenantId: 1
  });
};

// 打开和关闭新增对话框的函数在后面定义

// 重置编辑表单
const resetEditForm = () => {
  if (editFormRef.value) {
    editFormRef.value.resetFields();
  }
  Object.assign(editForm, {
    id: 0,
    cellId: 0,
    questionnaireName: "",
    questionnaireDescription: "",
    participationScope: "全体业主",
    publishTime: "",
    endTime: ""
  });
  activeEditTab.value = "info";
};

// 打开编辑问卷对话框
const openEditDialog = async (row: QuestionnaireSurveyListVo) => {
  try {
    editFormLoading.value = true;
    const response = await getQuestionnaireDetail(row.id);
    if (response.code === 0 || response.code === 200) {
      const data = response.data;
      if (data) {
        // 回显数据到编辑表单
        Object.assign(editForm, {
          id: data.id,
          cellId: data.cellId,
          questionnaireName: data.questionnaireName,
          questionnaireDescription: data.questionnaireDescription || "",
          participationScope: data.participationScope || "全体业主",
          publishTime: data.publishTime,
          endTime: data.endTime
        });

        // 加载问题列表
        const questionsResponse = await getQuestionsByQuestionnaireId(row.id);
        if (questionsResponse.code === 0 || questionsResponse.code === 200) {
          questions.value = questionsResponse.data || [];
          // 为每个问题获取选项数据
          for (const question of questions.value) {
            if (question.type === 1 || question.type === 3) {
              await fetchQuestionOptions(question.questionId);
            }
          }
        } else {
          ElMessage.error(questionsResponse.message || "获取问题列表失败");
          questions.value = [];
        }

        // 切换到问卷信息标签页
        activeEditTab.value = "info";

        editDialogVisible.value = true;
      } else {
        ElMessage.error("获取问卷详情失败：数据为空");
      }
    } else {
      ElMessage.error(response.message || "获取问卷详情失败");
    }
  } catch (error) {
    console.error("获取问卷详情失败:", error);
    ElMessage.error("获取问卷详情失败");
  } finally {
    editFormLoading.value = false;
  }
};

// 关闭编辑对话框
const closeEditDialog = () => {
  editDialogVisible.value = false;
  resetEditForm();
};

// 保存编辑问卷
const saveEditQuestionnaire = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();

    editFormLoading.value = true;
    const response = await updateQuestionnaire(editForm);

    if (response.code === 0 || response.code === 200) {
      ElMessage.success("更新问卷成功");
      closeEditDialog();
      fetchSurveyList(); // 重新获取列表
    } else {
      ElMessage.error(response.message || "更新问卷失败");
    }
  } catch (error: any) {
    // 表单验证失败不会走到这里
    if (error !== "cancel") {
      console.error("更新问卷失败:", error);
      ElMessage.error("更新问卷失败，请重试");
    }
  } finally {
    editFormLoading.value = false;
  }
};

// 打开新增对话框
const openAddDialog = () => {
  resetAddForm();
  addDialogVisible.value = true;
};

// 关闭新增对话框
const closeAddDialog = () => {
  addDialogVisible.value = false;
  resetAddForm();
};

// 保存新增问卷
const saveQuestionnaire = async () => {
  if (!addFormRef.value) return;

  try {
    await addFormRef.value.validate();

    addFormLoading.value = true;
    const response = await addQuestionnaire(addForm);

    if (response.code === 0 || response.code === 200) {
      ElMessage.success("新增问卷成功");
      closeAddDialog();
      fetchSurveyList(); // 重新获取列表
    } else {
      ElMessage.error(response.message || "新增问卷失败");
    }
  } catch (error: any) {
    // 表单验证失败不会走到这里
    if (error !== "cancel") {
      console.error("新增问卷失败:", error);
      ElMessage.error("新增问卷失败，请重试");
    }
  } finally {
    addFormLoading.value = false;
  }
};

// 获取问卷列表数据
const fetchSurveyList = async () => {
  loading.value = true;
  try {
    const params: QuestionnaireQueryParams = {
      page: pagination.page,
      limit: pagination.limit
    };

    let response;
    // 根据是否有关键词决定调用哪个接口
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value;
      response = await searchQuestionnaireByKeyword(params);
    } else {
      response = await getQuestionnaireList(params);
    }

    if (response.code === 0 || response.code === 200) {
      surveyList.value = response.data?.list || [];
      pagination.total = response.data?.total || 0;
    } else {
      ElMessage.error(response.message || "获取问卷列表失败");
    }
  } catch (error) {
    console.error("获取问卷列表失败:", error);
    ElMessage.error("获取问卷列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  pagination.page = 1;
  fetchSurveyList();
};

// 处理重置
const handleReset = () => {
  searchKeyword.value = "";
  pagination.page = 1;
  fetchSurveyList();
};

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchSurveyList();
};

// 处理页码变化
const handleCurrentChange = (current: number) => {
  pagination.page = current;
  fetchSurveyList();
};

// 重置新增问题表单
const resetAddQuestionForm = () => {
  if (addQuestionFormRef.value) {
    addQuestionFormRef.value.resetFields();
  }
  Object.assign(addQuestionForm, {
    questionnaireId: editForm.id,
    type: 1,
    question: "",
    isRequired: 1,
    sort: questions.value.length + 1
  });
};

// 打开新增问题对话框
const openAddQuestionDialog = () => {
  resetAddQuestionForm();
  addQuestionDialogVisible.value = true;
};

// 关闭新增问题对话框
const closeAddQuestionDialog = () => {
  addQuestionDialogVisible.value = false;
  resetAddQuestionForm();
};

// 保存新增问题
const saveQuestion = async () => {
  if (!addQuestionFormRef.value) return;

  try {
    await addQuestionFormRef.value.validate();

    addQuestionLoading.value = true;
    // 设置问卷ID和序号
    addQuestionForm.questionnaireId = editForm.id;
    addQuestionForm.sort = questions.value.length + 1;

    const response = await addQuestion(addQuestionForm);

    if (response.code === 0 || response.code === 200) {
      // 调用更新问题排序接口
      await updateQuestionSort(editForm.id);
      ElMessage.success("新增问题成功");
      // 重新获取问题列表以更新序号和数据
      const questionsResponse = await getQuestionsByQuestionnaireId(
        editForm.id
      );
      if (questionsResponse.code === 0 || questionsResponse.code === 200) {
        questions.value = questionsResponse.data || [];
        // 为每个问题获取选项数据
        for (const question of questions.value) {
          if (question.type === 1 || question.type === 3) {
            await fetchQuestionOptions(question.questionId);
          }
        }
      }
      closeAddQuestionDialog();
    } else {
      ElMessage.error(response.message || "新增问题失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("新增问题失败:", error);
      ElMessage.error("新增问题失败，请重试");
    }
  } finally {
    addQuestionLoading.value = false;
  }
};

// 编辑问题表单引用
const editQuestionFormRef = ref<InstanceType<typeof ElForm>>();

// 编辑问题对话框可见性
const editQuestionDialogVisible = ref(false);

// 编辑问题表单数据
const editQuestionForm = reactive<QuestionDto>({
  questionnaireId: 0,
  type: 1,
  question: "",
  isRequired: 1,
  sort: 1
});

// 当前编辑的问题ID
const currentQuestionId = ref(0);

// 重置编辑问题表单
const resetEditQuestionForm = () => {
  if (editQuestionFormRef.value) {
    editQuestionFormRef.value.resetFields();
  }
  Object.assign(editQuestionForm, {
    questionnaireId: editForm.id,
    type: 1,
    question: "",
    isRequired: 1,
    sort: 1
  });
  currentQuestionId.value = 0;
};

// 打开编辑问题对话框
const handleEditQuestion = async (row: QuestionDetailVo) => {
  // 填充表单数据
  currentQuestionId.value = row.questionId;
  Object.assign(editQuestionForm, {
    questionnaireId: row.questionnaireId,
    type: row.type,
    question: row.question,
    isRequired: row.isRequired,
    sort: row.sort
  });
  editQuestionDialogVisible.value = true;
};

// 关闭编辑问题对话框
const closeEditQuestionDialog = () => {
  editQuestionDialogVisible.value = false;
  resetEditQuestionForm();
};

// 保存编辑的问题
const saveEditedQuestion = async () => {
  if (!editQuestionFormRef.value || currentQuestionId.value === 0) return;

  try {
    await editQuestionFormRef.value.validate();

    const response = await updateQuestion(
      currentQuestionId.value,
      editQuestionForm
    );

    if (response.code === 0 || response.code === 200) {
      ElMessage.success("更新问题成功");
      // 重新获取问题列表
      const questionsResponse = await getQuestionsByQuestionnaireId(
        editForm.id
      );
      if (questionsResponse.code === 0 || questionsResponse.code === 200) {
        questions.value = questionsResponse.data || [];
        // 为每个问题获取选项数据
        for (const question of questions.value) {
          if (question.type === 1 || question.type === 3) {
            await fetchQuestionOptions(question.questionId);
          }
        }
      }
      closeEditQuestionDialog();
    } else {
      ElMessage.error(response.message || "更新问题失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("更新问题失败:", error);
      ElMessage.error("更新问题失败，请重试");
    }
  }
};

// 处理删除问题
const handleDeleteQuestion = (row: QuestionDetailVo) => {
  ElMessageBox.confirm(`确定要删除问题「${row.question}」吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        const response = await deleteQuestion(row.questionId);

        if (response.code === 0 || response.code === 200) {
          // 调用更新问题排序接口
          await updateQuestionSort(editForm.id);
          ElMessage.success("删除问题成功");
          // 重新获取问题列表
          const questionsResponse = await getQuestionsByQuestionnaireId(
            editForm.id
          );
          if (questionsResponse.code === 0 || questionsResponse.code === 200) {
            questions.value = questionsResponse.data || [];
          }
          // 移除该问题的选项缓存
          questionOptions.delete(row.questionId);
        } else {
          ElMessage.error(response.message || "删除问题失败");
        }
      } catch (error) {
        console.error("删除问题失败:", error);
        ElMessage.error("删除问题失败，请重试");
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};

// 根据sort字段对选项进行排序
const sortOptionsBySort = (questionId: number) => {
  const options = questionOptions.get(questionId) || [];
  return [...options].sort((a, b) => {
    // 确保sort是数字类型并进行比较
    // 0值排在最后，其他值按升序排列
    const sortA = Number(a.sort) || 0;
    const sortB = Number(b.sort) || 0;

    // 特殊处理0值，让0值排在最后
    if (sortA === 0 && sortB !== 0) return 1;
    if (sortA !== 0 && sortB === 0) return -1;

    return sortA - sortB;
  });
};

// 将数字转换为字母序号 (1-A, 2-B, 26-Z, 27-AA, 28-AB...)
const numberToLetter = (num: number): string => {
  let result = "";
  let n = Number(num) || 0;

  while (n > 0) {
    n--;
    const charCode = 65 + (n % 26); // 65 是 'A' 的ASCII码
    result = String.fromCharCode(charCode) + result;
    n = Math.floor(n / 26);
  }

  return result;
};

// 获取序号显示 (1-A, 2-B..., 0--)
const getOptionSequence = (sort: number): string => {
  if (Number(sort) === 0) {
    return "0--";
  }
  return `${sort}-${numberToLetter(sort)}`;
};

// 获取问题选项
const fetchQuestionOptions = async (questionId: number) => {
  if (!questionId) return;

  try {
    optionLoading.set(questionId, true);
    const response = await getAllQuestionOptions(questionId);
    if (response.code === 0 || response.code === 200) {
      questionOptions.set(questionId, response.data || []);
    } else {
      ElMessage.error(response.message || "获取选项失败");
    }
  } catch (error) {
    console.error("获取选项失败:", error);
    ElMessage.error("获取选项失败");
  } finally {
    optionLoading.set(questionId, false);
  }
};

// 打开新增选项对话框
const openAddOptionDialog = (question: QuestionDetailVo) => {
  currentQuestionForOption.value = question;

  // 获取当前问题的所有选项
  const options = questionOptions.get(question.questionId) || [];
  // 计算最大sort值，如果没有选项则默认为0
  const maxSort = options.reduce(
    (max, opt) => (opt.sort > max ? opt.sort : max),
    0
  );
  // 设置sort为最大sort+1（如果没有选项则为1）
  const defaultSort = maxSort + 1;

  Object.assign(addOptionForm, {
    questionId: question.questionId,
    content: "",
    sort: defaultSort
  });
  addOptionDialogVisible.value = true;
};

// 关闭新增选项对话框
const closeAddOptionDialog = () => {
  addOptionDialogVisible.value = false;
  addOptionForm.content = "";
  addOptionForm.questionId = 0;
  addOptionForm.sort = 0; // 重置sort值
};

// 保存问题选项
const saveQuestionOption = async () => {
  if (!addOptionForm.questionId || !addOptionForm.content?.trim()) {
    ElMessage.error("请填写选项内容");
    return;
  }

  try {
    // 获取当前问题的所有选项
    const options = questionOptions.get(addOptionForm.questionId) || [];
    // 计算最大sort值
    const maxSort = options.reduce(
      (max, opt) => (opt.sort > max ? opt.sort : max),
      0
    );
    // 设置sort为最大sort+1
    addOptionForm.sort = maxSort + 1;

    addOptionLoading.value = true;
    const response = await addQuestionOption(addOptionForm as QuestionOption);

    if (response.code === 0 || response.code === 200) {
      ElMessage.success("新增选项成功");
      // 重新获取该问题的选项列表
      if (addOptionForm.questionId) {
        await fetchQuestionOptions(addOptionForm.questionId);
        await updateQuestionOptionsSort(addOptionForm.questionId);
      }
      closeAddOptionDialog();
    } else {
      ElMessage.error(response.message || "新增选项失败");
    }
  } catch (error) {
    console.error("新增选项失败:", error);
    ElMessage.error("新增选项失败，请重试");
  } finally {
    addOptionLoading.value = false;
  }
};

// 打开编辑选项对话框
const openEditOptionDialog = (option: QuestionOption) => {
  currentOptionId.value = option.id;

  // 获取当前问题的所有选项
  const options = questionOptions.get(option.questionId) || [];
  // 计算最大sort值
  const maxSort = options.reduce((max, opt) => {
    // 排除当前正在编辑的选项，避免自己和自己比较
    if (opt.id !== option.id && opt.sort > max) {
      return opt.sort;
    }
    return max;
  }, 0);

  // 设置sort为最大sort+1
  const newSort = maxSort + 1;

  Object.assign(editOptionForm, {
    id: option.id,
    questionId: option.questionId,
    content: option.content,
    sort: newSort
  });
  editOptionDialogVisible.value = true;
};

// 关闭编辑选项对话框
const closeEditOptionDialog = () => {
  editOptionDialogVisible.value = false;
  Object.assign(editOptionForm, {
    id: 0,
    questionId: 0,
    content: "",
    sort: 1
  });
  currentOptionId.value = 0;
};

// 保存编辑的选项
const saveEditedOption = async () => {
  if (!editOptionForm.content?.trim()) {
    ElMessage.error("请填写选项内容");
    return;
  }

  try {
    editOptionLoading.value = true;
    const response = await updateQuestionOption(editOptionForm);

    if (response.code === 0 || response.code === 200) {
      ElMessage.success("更新选项成功");
      await updateQuestionOptionsSort(editOptionForm.questionId);
      // 重新获取该问题的选项列表
      await fetchQuestionOptions(editOptionForm.questionId);
      closeEditOptionDialog();
    } else {
      ElMessage.error(response.message || "更新选项失败");
    }
  } catch (error) {
    console.error("更新选项失败:", error);
    ElMessage.error("更新选项失败，请重试");
  } finally {
    editOptionLoading.value = false;
  }
};

// 删除选项
const deleteOption = (option: QuestionOption) => {
  ElMessageBox.confirm(`确定要删除选项「${option.content}」吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        const response = await deleteQuestionOption(option.id);
        if (response.code === 0 || response.code === 200) {
          ElMessage.success("删除选项成功");
          await updateQuestionOptionsSort(option.questionId);
          // 重新获取该问题的选项列表
          await fetchQuestionOptions(option.questionId);
        } else {
          ElMessage.error(response.message || "删除选项失败");
        }
      } catch (error) {
        console.error("删除选项失败:", error);
        ElMessage.error("删除选项失败，请重试");
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};

// 处理新增问卷
const handleAdd = () => {
  openAddDialog();
};

// 问卷详情相关状态
const detailDialogVisible = ref(false);
const detailLoading = ref(false);
const currentQuestionnaire = ref<QuestionnaireSurveyListVo | null>(null);
const questionnaireQuestions = ref<QuestionDetailVo[]>([]);
const questionOptionsMap = ref<Map<number, QuestionOption[]>>(new Map());

// 获取问卷详情及问题选项
const fetchQuestionnaireDetail = async (id: number) => {
  detailLoading.value = true;
  try {
    // 获取问卷基本信息
    const questionnaireResponse = await getQuestionnaireDetail(id);
    if (
      questionnaireResponse.code === 0 ||
      questionnaireResponse.code === 200
    ) {
      let questionnaireData = questionnaireResponse.data;

      // 如果没有小区名称，尝试从列表中查找对应的小区名称
      if (!questionnaireData?.cellName && questionnaireData?.cellId) {
        // 查找当前问卷ID在列表中的对应项
        const listItem = surveyList.value.find(item => item.id === id);
        if (listItem && listItem.cellName) {
          questionnaireData = {
            ...questionnaireData,
            cellName: listItem.cellName
          };
        }
      }

      currentQuestionnaire.value = questionnaireData;
    }

    // 获取问题列表
    const questionsResponse = await getQuestionsByQuestionnaireId(id);
    if (questionsResponse.code === 0 || questionsResponse.code === 200) {
      questionnaireQuestions.value = questionsResponse.data || [];

      // 获取每个问题的选项
      for (const question of questionnaireQuestions.value) {
        if (question.type === 1 || question.type === 3) {
          // 单选或多选才获取选项
          const optionsResponse = await getAllQuestionOptions(
            question.questionId
          );
          if (optionsResponse.code === 0 || optionsResponse.code === 200) {
            // 按sort排序选项
            const sortedOptions =
              optionsResponse.data?.sort(
                (a, b) => (a.sort || 0) - (b.sort || 0)
              ) || [];
            questionOptionsMap.value.set(question.questionId, sortedOptions);
          }
        }
      }
    }
  } catch (error) {
    console.error("获取问卷详情失败:", error);
    ElMessage.error("获取问卷详情失败");
  } finally {
    detailLoading.value = false;
  }
};

// 处理查看问卷
const handleView = async (row: QuestionnaireSurveyListVo) => {
  await fetchQuestionnaireDetail(row.id);
  detailDialogVisible.value = true;
};

// 关闭详情对话框
const closeDetailDialog = () => {
  detailDialogVisible.value = false;
  currentQuestionnaire.value = null;
  questionnaireQuestions.value = [];
  questionOptionsMap.value.clear();
};

// 获取问题类型文本
const getQuestionTypeText = (type: number): string => {
  switch (type) {
    case 1:
      return "单选题";
    case 2:
      return "填空题";
    case 3:
      return "多选题";
    default:
      return "未知类型";
  }
};

// 获取是否必填文本
const getRequiredText = (isRequired: number): string => {
  return isRequired === 1 ? "必填" : "选填";
};

// 获取选项字母标识
const getOptionLetter = (index: number): string => {
  return String.fromCharCode(65 + index); // A, B, C, ...
};

// 处理统计
const handleStatistics = (row: QuestionnaireSurveyListVo) => {
  console.log("统计问卷:", row);
  ElMessage.info("统计功能开发中");
};

// 处理删除
const handleDelete = async (row: QuestionnaireSurveyListVo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除问卷「${row.questionnaireName}」吗？此操作不可撤销。`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    loading.value = true;
    console.log("准备删除问卷，ID:", row.id);
    const response = await deleteQuestionnaire(row.id);

    if (response.code === 0 || response.code === 200) {
      ElMessage.success("删除成功");
      // 重新获取列表
      fetchSurveyList();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error: any) {
    // 如果用户取消，则不显示错误
    if (error === "cancel") return;
    console.error("删除问卷失败:", error);
    ElMessage.error("删除失败，请重试");
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchSurveyList();
  fetchCellList();
});
</script>

<style scoped>
/* 问卷详情样式 */
.questionnaire-detail-container {
  padding: 20px 0;
}

.questionnaire-info-section,
.questionnaire-preview-section {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.questionnaire-info-section h3,
.questionnaire-preview-section h3 {
  margin-bottom: 20px;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 10px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-label {
  color: #606266;
  font-weight: 500;
  margin-right: 10px;
  min-width: 100px;
}

.info-value {
  color: #303133;
  word-break: break-all;
}

.description-section {
  margin-top: 20px;
}

.description-section .info-value {
  margin-top: 8px;
  line-height: 1.6;
}

/* 问题预览样式 */
.questions-container {
  margin-top: 20px;
}

.question-item {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.question-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.question-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.question-number {
  font-weight: bold;
  color: #303133;
  margin-right: 5px;
}

.question-content {
  color: #303133;
  font-size: 15px;
  line-height: 1.6;
}

.required-mark {
  color: #f56c6c;
  margin-left: 4px;
}

.question-meta {
  margin-bottom: 15px;
  display: flex;
  gap: 15px;
}

.question-type,
.question-required {
  padding: 2px 8px;
  background-color: #ecf5ff;
  color: #409eff;
  border-radius: 4px;
  font-size: 12px;
}

.question-required {
  background-color: #fdf6ec;
  color: #e6a23c;
}

/* 选项样式 */
.options-container {
  margin-top: 10px;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 10px;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.option-item:hover {
  background-color: #f5f7fa;
}

.option-marker {
  display: flex;
  align-items: center;
  margin-right: 15px;
  min-width: 40px;
}

.radio-marker,
.checkbox-marker {
  font-size: 18px;
  color: #c0c4cc;
  margin-right: 5px;
}

.option-letter {
  font-weight: bold;
  color: #606266;
  width: 20px;
  text-align: center;
}

.option-content {
  color: #303133;
  line-height: 1.5;
}

/* 填空题样式 */
.blank-preview {
  margin-top: 15px;
}

.blank-input-preview {
  padding: 10px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  color: #909399;
  background-color: #f8f9fa;
  font-style: italic;
}

.empty-tip {
  text-align: center;
  padding: 40px 0;
}
</style>

<template>
  <div class="survey-container">
    <!-- 搜索和操作栏 -->
    <div class="survey-header">
      <div class="left-section">
        <el-button type="primary" @click="handleAdd" class="add-button">
          <el-icon><Plus /></el-icon>
          新增问卷
        </el-button>
      </div>
      <div
        class="search-section"
        style="display: flex; align-items: center; gap: 10px"
      >
        <el-input
          v-model="searchKeyword"
          placeholder="请输入小区/问卷名称/状态"
          clearable
          @keyup.enter="handleSearch"
          style="width: 300px"
        />
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 问卷列表 -->
    <el-table v-loading="loading" :data="surveyList" style="width: 100%" border>
      <el-table-column prop="cellName" label="小区" min-width="120">
        <template #default="{ row }">
          <span>{{ row.cellName || "-" }}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="questionnaireName"
        label="问卷名称"
        min-width="180"
      >
        <template #default="{ row }">
          <span>{{ row.questionnaireName || "-" }}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="questionnaireDescription"
        label="问卷描述"
        min-width="200"
      >
        <template #default="{ row }">
          <span>{{ row.questionnaireDescription || "-" }}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="participationScope"
        label="参与范围"
        min-width="120"
      >
        <template #default="{ row }">
          <span>{{ row.participationScope || "-" }}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="questionCount"
        label="问题数量"
        min-width="100"
        align="center"
      >
        <template #default="{ row }">
          <span>{{ row.questionCount || 0 }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="publishTime" label="发布时间" min-width="150">
        <template #default="{ row }">
          <span>{{ row.publishTime || "-" }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="endTime" label="结束时间" min-width="150">
        <template #default="{ row }">
          <span>{{ row.endTime || "-" }}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="answerCount"
        label="答卷数量"
        min-width="100"
        align="center"
      >
        <template #default="{ row }">
          <span>{{ row.answerCount || "--" }}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="status"
        label="状态"
        min-width="100"
        align="center"
      >
        <template #default="{ row }">
          <span>{{ row.status || "-" }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" min-width="180" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleView(row)"
            >详情</el-button
          >
          <el-button size="small" @click="openEditDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 问卷详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="currentQuestionnaire?.questionnaireName || '问卷详情'"
      :width="'54%'"
      :fullscreen="false"
      :before-close="closeDetailDialog"
    >
      <div v-loading="detailLoading" class="questionnaire-detail-container">
        <!-- 问卷基本信息 -->
        <div class="questionnaire-info-section">
          <h3>问卷基本信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="info-label">问卷名称：</span>
              <span class="info-value">{{
                currentQuestionnaire?.questionnaireName || "-"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">所属小区：</span>
              <span class="info-value">{{
                currentQuestionnaire?.cellName || "-"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">参与范围：</span>
              <span class="info-value">{{
                currentQuestionnaire?.participationScope || "-"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">问题数量：</span>
              <span class="info-value">{{
                currentQuestionnaire?.questionCount || 0
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">发布时间：</span>
              <span class="info-value">{{
                currentQuestionnaire?.publishTime || "-"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">结束时间：</span>
              <span class="info-value">{{
                currentQuestionnaire?.endTime || "-"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">答卷数量：</span>
              <span class="info-value">{{
                currentQuestionnaire?.answerCount || "--"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">当前状态：</span>
              <span class="info-value">{{
                currentQuestionnaire?.status || "-"
              }}</span>
            </div>
          </div>
          <div class="description-section">
            <span class="info-label">问卷描述：</span>
            <p class="info-value">
              {{ currentQuestionnaire?.questionnaireDescription || "-" }}
            </p>
          </div>
        </div>

        <!-- 问卷问题预览 -->
        <div class="questionnaire-preview-section">
          <h3>问卷预览</h3>
          <div v-if="questionnaireQuestions.length === 0" class="empty-tip">
            <el-empty description="暂无问题" />
          </div>
          <div v-else class="questions-container">
            <div
              v-for="question in questionnaireQuestions"
              :key="question.questionId"
              class="question-item"
            >
              <div class="question-header">
                <span class="question-number">{{ question.sort }}. </span>
                <span class="question-content">
                  {{ question.question }}
                  <span v-if="question.isRequired === 1" class="required-mark"
                    >*</span
                  >
                </span>
              </div>
              <div class="question-meta">
                <span class="question-type">{{
                  getQuestionTypeText(question.type)
                }}</span>
                <span class="question-required">{{
                  getRequiredText(question.isRequired)
                }}</span>
              </div>

              <!-- 选项预览 -->
              <div
                v-if="question.type === 1 || question.type === 3"
                class="options-container"
              >
                <div
                  v-for="(option, index) in questionOptionsMap.get(
                    question.questionId
                  )"
                  :key="option.id"
                  class="option-item"
                >
                  <div class="option-marker">
                    <span v-if="question.type === 1" class="radio-marker"
                      >○</span
                    >
                    <span v-else class="checkbox-marker">□</span>
                    <span class="option-letter">{{
                      getOptionLetter(index)
                    }}</span>
                  </div>
                  <span class="option-content">{{ option.content }}</span>
                </div>
              </div>

              <!-- 填空题预览 -->
              <div v-else-if="question.type === 2" class="blank-preview">
                <div class="blank-input-preview">（请在此填写答案）</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="closeDetailDialog">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增问卷对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增问卷"
      width="800px"
      @close="closeAddDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="100px"
        :rules="{
          cellId: [
            { required: true, message: '请选择小区', trigger: 'change' }
          ],
          questionnaireName: [
            { required: true, message: '请输入问卷名称', trigger: 'blur' }
          ],
          publishTime: [
            { required: true, message: '请选择发布时间', trigger: 'change' }
          ],
          endTime: [
            { required: true, message: '请选择结束时间', trigger: 'change' }
          ]
        }"
      >
        <el-form-item label="小区" prop="cellId">
          <el-select
            v-model="addForm.cellId"
            placeholder="请选择小区"
            :loading="communityLoading"
          >
            <el-option
              v-for="community in communities"
              :key="community.id"
              :label="community.name"
              :value="community.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="问卷名称" prop="questionnaireName">
          <el-input
            v-model="addForm.questionnaireName"
            placeholder="请输入问卷名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="问卷描述" prop="questionnaireDescription">
          <el-textarea
            v-model="addForm.questionnaireDescription"
            placeholder="请输入问卷描述"
            maxlength="500"
            show-word-limit
            :rows="3"
          />
        </el-form-item>

        <el-form-item label="参与范围" prop="participationScope">
          <el-input
            v-model="addForm.participationScope"
            placeholder="请输入参与范围，默认为全体业主"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
            v-model="addForm.publishTime"
            type="datetime"
            placeholder="请选择发布时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="addForm.endTime"
            type="datetime"
            placeholder="请选择结束时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeAddDialog">取消</el-button>
          <el-button
            type="primary"
            @click="saveQuestionnaire"
            :loading="addFormLoading"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="editDialogVisible"
      title="编辑问卷"
      width="1000px"
      @close="closeEditDialog"
      :close-on-click-modal="false"
    >
      <!-- 编辑选项卡 -->
      <el-radio-group
        v-model="activeEditTab"
        size="large"
        style="margin-bottom: 20px"
      >
        <el-radio-button label="info">编辑问卷信息</el-radio-button>
        <el-radio-button label="questions">编辑问题信息</el-radio-button>
      </el-radio-group>

      <!-- 编辑问卷信息 -->
      <div v-if="activeEditTab === 'info'">
        <el-form
          ref="editFormRef"
          :model="editForm"
          label-width="100px"
          :rules="{
            cellId: [
              { required: true, message: '请选择小区', trigger: 'change' }
            ],
            questionnaireName: [
              { required: true, message: '请输入问卷名称', trigger: 'blur' }
            ],
            publishTime: [
              { required: true, message: '请选择发布时间', trigger: 'change' }
            ],
            endTime: [
              { required: true, message: '请选择结束时间', trigger: 'change' }
            ]
          }"
        >
          <el-form-item label="小区" prop="cellId">
            <el-select
              v-model="editForm.cellId"
              placeholder="请选择小区"
              :loading="communityLoading"
            >
              <el-option
                v-for="community in communities"
                :key="community.id"
                :label="community.name"
                :value="community.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="问卷名称" prop="questionnaireName">
            <el-input
              v-model="editForm.questionnaireName"
              placeholder="请输入问卷名称"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="问卷描述" prop="questionnaireDescription">
            <el-textarea
              v-model="editForm.questionnaireDescription"
              placeholder="请输入问卷描述"
              maxlength="500"
              show-word-limit
              :rows="3"
            />
          </el-form-item>

          <el-form-item label="参与范围" prop="participationScope">
            <el-input
              v-model="editForm.participationScope"
              placeholder="请输入参与范围，默认为全体业主"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="发布时间" prop="publishTime">
            <el-date-picker
              v-model="editForm.publishTime"
              type="datetime"
              placeholder="请选择发布时间"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="editForm.endTime"
              type="datetime"
              placeholder="请选择结束时间"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 编辑问题信息 -->
      <div v-else-if="activeEditTab === 'questions'">
        <!-- 操作按钮 -->
        <div style="margin-bottom: 20px; text-align: right">
          <el-button type="primary" @click="openAddQuestionDialog">
            <el-icon><Plus /></el-icon>
            新增问题
          </el-button>
        </div>

        <!-- 问题列表 -->
        <div v-if="questions.length > 0" style="margin-bottom: 20px">
          <!-- 问题列表 -->
          <div
            v-for="question in questions"
            :key="question.questionId"
            class="question-item"
          >
            <el-table :data="[question]" style="width: 100%; margin-bottom: 0">
              <el-table-column prop="sort" label="题号" width="80" />
              <el-table-column prop="question" label="问题内容" min-width="400">
                <template #default="{ row }">
                  <span>{{ row.question }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="type" label="问题类型" width="80">
                <template #default="{ row }">
                  <span>{{
                    row.type === 1 ? "单选" : row.type === 2 ? "填空" : "多选"
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="isRequired" label="是否必填" width="80">
                <template #default="{ row }">
                  <span>{{ row.isRequired === 1 ? "必填" : "选填" }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="240" fixed="right">
                <template #default="{ row }">
                  <el-button size="small" @click="handleEditQuestion(row)">
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleDeleteQuestion(row)"
                  >
                    删除
                  </el-button>
                  <el-button
                    v-if="row.type === 1 || row.type === 3"
                    size="small"
                    type="primary"
                    @click="openAddOptionDialog(row)"
                  >
                    新增选项
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 问题对应的选项列表 -->
            <div
              v-if="question.type === 1 || question.type === 3"
              class="options-container"
            >
              <div
                v-if="optionLoading.get(question.questionId)"
                class="option-loading"
              >
                <el-skeleton :rows="3" animated />
              </div>
              <div
                v-if="
                  questionOptions.has(question.questionId) &&
                  questionOptions.get(question.questionId)?.length > 0
                "
                class="options-list"
              >
                <div
                  v-for="option in sortOptionsBySort(question.questionId)"
                  :key="option.id"
                  class="option-item"
                >
                  <span style="flex: 1">{{ option.content }}</span>
                  <div class="option-actions">
                    <span class="option-sequence" style="margin-right: 10px">{{
                      getOptionSequence(option.sort)
                    }}</span>
                    <el-button
                      size="small"
                      @click="openEditOptionDialog(option)"
                      >编辑</el-button
                    >
                    <el-button
                      size="small"
                      type="danger"
                      @click="deleteOption(option)"
                      >删除</el-button
                    >
                  </div>
                </div>
              </div>
              <div v-else class="no-options">
                <!-- 不需要在此处显示新增选项按钮，因为已经在问题行的操作列中提供了 -->
              </div>
            </div>
          </div>
        </div>

        <!-- 无问题提示 -->
        <div v-else style="text-align: center; padding: 40px; color: #909399">
          <p>暂无问题，请点击"新增问题"按钮添加</p>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeEditDialog">取消</el-button>
          <el-button
            type="primary"
            @click="activeEditTab === 'info' ? saveEditQuestionnaire() : handleQuestionsConfirm()"
            :loading="editFormLoading"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 编辑问题对话框 -->
    <el-dialog
      v-model="editQuestionDialogVisible"
      title="编辑问题"
      width="600px"
      @close="closeEditQuestionDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editQuestionFormRef"
        :model="editQuestionForm"
        label-width="100px"
        :rules="{
          question: [
            { required: true, message: '请输入问题内容', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '请选择问题类型', trigger: 'change' }
          ],
          isRequired: [
            { required: true, message: '请选择是否必填', trigger: 'change' }
          ],
          sort: [{ required: true, message: '请输入问题序号', trigger: 'blur' }]
        }"
      >
        <el-form-item label="问题序号" prop="sort">
          <el-input-number v-model="editQuestionForm.sort" :min="0" :step="1" />
        </el-form-item>

        <el-form-item label="问题内容" prop="question">
          <el-input
            v-model="editQuestionForm.question"
            type="textarea"
            :rows="3"
            placeholder="请输入问题内容"
          />
        </el-form-item>

        <el-form-item label="问题类型" prop="type">
          <el-radio-group v-model="editQuestionForm.type">
            <el-radio :label="1">单选</el-radio>
            <el-radio :label="2">填空</el-radio>
            <el-radio :label="3">多选</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否必填" prop="isRequired">
          <el-radio-group v-model="editQuestionForm.isRequired">
            <el-radio :label="1">必填</el-radio>
            <el-radio :label="0">选填</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeEditQuestionDialog">取消</el-button>
          <el-button type="primary" @click="saveEditedQuestion">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 新增问题对话框 -->
    <el-dialog
      v-model="addQuestionDialogVisible"
      title="新增问题"
      width="600px"
      @close="closeAddQuestionDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addQuestionFormRef"
        :model="addQuestionForm"
        label-width="100px"
        :rules="{
          question: [
            { required: true, message: '请输入问题内容', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '请选择问题类型', trigger: 'change' }
          ],
          isRequired: [
            { required: true, message: '请指定是否必填', trigger: 'change' }
          ]
        }"
      >
        <el-form-item label="问题序号" prop="sort" disabled>
          <el-input v-model="addQuestionForm.sort" readonly />
        </el-form-item>

        <el-form-item label="问题内容" prop="question">
          <el-input
            v-model="addQuestionForm.question"
            type="textarea"
            placeholder="请输入问题内容"
            :rows="3"
          />
        </el-form-item>

        <el-form-item label="问题类型" prop="type">
          <el-radio-group v-model="addQuestionForm.type">
            <el-radio :label="1">单选</el-radio>
            <el-radio :label="2">填空</el-radio>
            <el-radio :label="3">多选</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否必填" prop="isRequired">
          <el-radio-group v-model="addQuestionForm.isRequired">
            <el-radio :label="0">选填</el-radio>
            <el-radio :label="1">必填</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeAddQuestionDialog">取消</el-button>
          <el-button
            type="primary"
            @click="saveQuestion"
            :loading="addQuestionLoading"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增选项对话框 -->
    <el-dialog
      v-model="addOptionDialogVisible"
      title="新增选项"
      width="400px"
      :before-close="closeAddOptionDialog"
    >
      <el-form label-width="80px">
        <el-form-item label="问题名称">
          <el-input
            :value="currentQuestionForOption?.question || ''"
            disabled
          />
        </el-form-item>
        <el-form-item label="选项内容" required>
          <el-input
            v-model="addOptionForm.content"
            placeholder="请输入选项内容"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="排序值">
          <el-input-number
            v-model="addOptionForm.sort"
            :min="0"
            placeholder="请输入排序值"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeAddOptionDialog">取消</el-button>
        <el-button
          type="primary"
          :loading="addOptionLoading"
          @click="saveQuestionOption"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑选项对话框 -->
    <el-dialog
      v-model="editOptionDialogVisible"
      title="编辑选项"
      width="400px"
      :before-close="closeEditOptionDialog"
    >
      <el-form label-width="80px">
        <el-form-item label="选项内容" required>
          <el-input
            v-model="editOptionForm.content"
            placeholder="请输入选项内容"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="排序值">
          <el-input-number
            v-model="editOptionForm.sort"
            :min="1"
            placeholder="请输入排序值"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeEditOptionDialog">取消</el-button>
        <el-button
          type="primary"
          :loading="editOptionLoading"
          @click="saveEditedOption"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.survey-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.question-item {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.options-container {
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-top: 1px solid #ebeef5;
}

.option-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  margin-bottom: 8px;
  background-color: #ffffff;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.option-item:last-child {
  margin-bottom: 0;
}

.option-actions {
  display: flex;
  gap: 8px;
}

.option-loading {
  padding: 20px;
}

.no-options {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.survey-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.left-section {
  display: flex;
  gap: 10px;
}

.add-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

.search-section {
  display: flex;
  align-items: center;
}

:deep(.el-table) {
  background-color: #ffffff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #606266;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

:deep(.el-pagination) {
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .survey-header {
    flex-direction: column;
    gap: 15px;
  }

  .search-section {
    width: 100%;
  }

  .search-section :deep(.el-input) {
    width: 100% !important;
  }
}
</style>
